package approve.action;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import memo.action.Memo_listview;
import model.pojo.Employee;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import approve.adapter.Library_Listview_Adapter;
import approve.dao.ListLabelDAO;
import approve.model.Approvedoc;
import approve.model.ListLabel;

public class Library_All_Label extends Activity {

	LinearLayout lilaaddlabel;
	RelativeLayout relaeditlabel,relaaddlabel;
	TextView logout,username,home,welcome,la_headerTitle,lbnamelabel;
	Button buttonBack,btaddlabel,btresetlabel,btcloselabel,btaddnewlabel,bteditlabel,btcanceleditlabel,btdeletelabel;
	EditText txtnamelabel;
	ListView lstalllabel;
	ArrayList<ListLabel> listlabelvalue = new ArrayList<ListLabel>();
	ListLabelDAO listlabeldao = new ListLabelDAO();
	Library_Listview_Adapter libarylistadapter;
	ListLabel onelabel;
	int pos=0;
	int kq=-1;
	List<Approvedoc> lstAppDoc;

	final Handler uiHandler2=new Handler();
	boolean isUpdateRequired2=false;
	AlertDialog alertwaiting2;
	TextView tvwaiting;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	
	public boolean isUpdateRequired2() {
		return isUpdateRequired2;
	}
	public ListLabelDAO getListlabeldao() {
		return listlabeldao;
	}
	public void setListlabeldao(ListLabelDAO listlabeldao) {
		this.listlabeldao = listlabeldao;
	}
	public Library_Listview_Adapter getLibarylistadapter() {
		return libarylistadapter;
	}
	public void setLibarylistadapter(Library_Listview_Adapter libarylistadapter) {
		this.libarylistadapter = libarylistadapter;
	}
	public ListView getLstalllabel() {
		return lstalllabel;
	}
	public void setLstalllabel(ListView lstalllabel) {
		this.lstalllabel = lstalllabel;
	}
	public ArrayList<ListLabel> getListlabelvalue() {
		return listlabelvalue;
	}
	public void setListlabelvalue(ArrayList<ListLabel> listlabelvalue) {
		this.listlabelvalue = listlabelvalue;
	}

	public void setUpdateRequired2(boolean isUpdateRequired2) {
		this.isUpdateRequired2 = isUpdateRequired2;
	}

	public AlertDialog getAlertwaiting2() {
		return alertwaiting2;
	}

	public void setAlertwaiting2(AlertDialog alertwaiting2) {
		this.alertwaiting2 = alertwaiting2;
	}

	public Handler getUiHandler2() {
		return uiHandler2;
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try{
			initall();
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}

	private void initall(){
		setContentView(R.layout.library_all_label);
		getInitAttribute();
		loadlistview();
		Library_All_Label.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.relativeTitle);

		Resources res = getResources();
		final BitmapDrawable background = (BitmapDrawable) res.getDrawable(R.drawable.bg_menu_item);
		background.setTileModeX(Shader.TileMode.REPEAT);
		background.setTileModeY(Shader.TileMode.REPEAT);
		background.setDither(true);
		relativeLayout.setBackgroundDrawable(background);

		buttonBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				buttonBack.setBackgroundResource(R.drawable.bg_back_pressed);
				Intent intent = new Intent(Library_All_Label.this,MainEApproval.class);
				startActivity(intent);
				finish();
			}
		});
	}
	
	public void processItemClickListerner(ListLabel listLabel){
		Intent intent = new Intent(Library_All_Label.this,Library_Label_Item.class);
		intent.putExtra("label", listLabel);
		startActivity(intent);
		finish();
	}
	

	private void getInitAttribute(){
		logout=(TextView)findViewById(R.id.logout);
		logout.setText(LoginActivity.lang.getString("Logout"));
		username=(TextView)findViewById(R.id.username);
		username.setText(LoginActivity.emp.getUserName());
		welcome = (TextView)findViewById(R.id.welcome);
		welcome.setText(LoginActivity.lang.getString("ac_Welcome"));
		buttonBack = (Button)findViewById(R.id.buttonBack);
		la_headerTitle=(TextView)findViewById(R.id.la_headerTitle);
		la_headerTitle.setText(LoginActivity.lang.getString("library_document"));

		lilaaddlabel =(LinearLayout)findViewById(R.id.lilaaddlabel);
		btaddnewlabel =(Button)findViewById(R.id.btaddnewlabel);
		btaddnewlabel.setText(LoginActivity.lang.getString("new_lable"));
		lbnamelabel=(TextView)findViewById(R.id.lbnamelabel);
		lbnamelabel.setText(LoginActivity.lang.getString("name"));
		txtnamelabel=(EditText)findViewById(R.id.txtnamelabel);
		btaddlabel=(Button)findViewById(R.id.btaddlabel);
		btaddlabel.setText(LoginActivity.lang.getString("add"));
		btresetlabel =(Button)findViewById(R.id.btresetlabel);
		btresetlabel.setText(LoginActivity.lang.getString("ac_ma_Reset"));
		btcloselabel =(Button)findViewById(R.id.btcloselabel);
		btcloselabel.setText(LoginActivity.lang.getString("Close"));
		lstalllabel=(ListView)findViewById(R.id.lstalllabel);
		
		relaeditlabel=(RelativeLayout)findViewById(R.id.relaeditlabel);
		relaaddlabel=(RelativeLayout)findViewById(R.id.relaaddlabel);
		bteditlabel=(Button)findViewById(R.id.bteditlabel);
		btcanceleditlabel=(Button)findViewById(R.id.btcanceleditlabel);
		btdeletelabel=(Button)findViewById(R.id.btdeletelabel);
		bteditlabel.setText(LoginActivity.lang.getString("Edit"));
		btcanceleditlabel.setText(LoginActivity.lang.getString("cancel"));
		btdeletelabel.setText(LoginActivity.lang.getString("Delete"));

		logout.setOnClickListener(listenerLogout);
		btaddlabel.setOnClickListener(btaddlabelClick);
		btresetlabel.setOnClickListener(btresetlabelClick);
		btcloselabel.setOnClickListener(btcloselabelClick);
		btaddnewlabel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				txtnamelabel.setText("");
				lilaaddlabel.setVisibility(View.VISIBLE);
				relaaddlabel.setVisibility(View.VISIBLE);
				relaeditlabel.setVisibility(View.GONE);
				txtnamelabel.setFocusable(true);
				Library_All_Label.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			}
		});
		bteditlabel.setOnClickListener(bteditlabelClick);
		btcanceleditlabel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				lilaaddlabel.setVisibility(View.GONE);
				onelabel= new ListLabel();
			}
		});
		btdeletelabel.setOnClickListener(btdeletelabelClick);
		
		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaiting.setText(LoginActivity.lang.getString("waiting")+"...");

		builderwaiting = new AlertDialog.Builder(Library_All_Label.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting2 = builderwaiting.create();

	}
	
	public void longClickEditLabel(ListLabel lila,int ps){
		alertwaiting2.show();
		onelabel = lila;
		pos=ps;
		try{
			new Thread(){
				public void run() {
					onelabel.getNumber(LoginActivity.database,LoginActivity.emp.getIdemployee());
					uiHandler2.post( new Runnable(){
						@Override
						public void run() {
							if(isUpdateRequired2){
							}else{
								txtnamelabel.setText(onelabel.getName_lable());
								lilaaddlabel.setVisibility(View.VISIBLE);
								relaaddlabel.setVisibility(View.GONE);
								relaeditlabel.setVisibility(View.VISIBLE);
								txtnamelabel.setFocusable(true);
								Library_All_Label.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
								alertwaiting2.cancel();
							}
						}
					} );
				}
			}.start();
		}catch (Exception e) {}
		
	}
	
	private OnClickListener btdeletelabelClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			kq=0;
			if(onelabel.getNumber()>0){
				AlertDialog.Builder builder = new AlertDialog.Builder(Library_All_Label.this);
				builder.setTitle(LoginActivity.lang.getString("warning"));
				builder.setMessage(LoginActivity.lang.getString("notdelete"));
				builder.setCancelable(false);
				builder.setPositiveButton(LoginActivity.lang.getString("ok"), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						alertwaiting2.show();

						try{
							new Thread(){
								public void run() {
									processItemClickListerner(onelabel);
									uiHandler2.post( new Runnable(){
										@Override
										public void run() {
											if(isUpdateRequired2){
											}else{
												alertwaiting2.cancel();
											}
										}
									} );
								}
							}.start();
						}catch (Exception e) {}
					}
					
				});
				builder.setNegativeButton(LoginActivity.lang.getString("cancel"), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
					}
				});
				
				
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}else{
				AlertDialog.Builder builder = new AlertDialog.Builder(Library_All_Label.this);
				builder.setTitle(LoginActivity.lang.getString("Delete"));
				builder.setMessage(LoginActivity.lang.getString("areyousure")+" ?");
				builder.setCancelable(false);
				builder.setPositiveButton(LoginActivity.lang.getString("ok"), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						alertwaiting2.show();
						try{
							new Thread(){
								public void run() {
									try {
										kq=listlabeldao.deleteLabel(LoginActivity.database, onelabel.getId());
									} catch (SQLException e) {
										e.printStackTrace();
									}
									uiHandler2.post( new Runnable(){
										@Override
										public void run() {
											if(isUpdateRequired2){
											}else{
												if(kq>0){
													loadlistview();
													lilaaddlabel.setVisibility(View.GONE);
													onelabel= new ListLabel();
												}
												alertwaiting2.cancel();
											}
										}
									} );
								}
							}.start();
						}catch (Exception e) {}
					}
				});
				builder.setNegativeButton(LoginActivity.lang.getString("cancel"), new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {

					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
		}
	};
		
	
	
	private OnClickListener bteditlabelClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Library_All_Label.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			kq=0;
			if(txtnamelabel.getText()!= null && !txtnamelabel.getText().toString().equals("")){
				alertwaiting2.show();
				try{
					new Thread(){
						public void run() {
							try {
								kq=listlabeldao.updateLabel(LoginActivity.database,onelabel.getId(), txtnamelabel.getText().toString());
							} catch (SQLException e) {
								e.printStackTrace();
							}
							uiHandler2.post( new Runnable(){
								@Override
								public void run() {
									if(isUpdateRequired2){
									}else{
										if(kq>0){
											listlabelvalue.get(pos).setName_lable(txtnamelabel.getText().toString());
											libarylistadapter.notifyDataSetChanged();
											lilaaddlabel.setVisibility(View.GONE);
											onelabel= new ListLabel();
										}
										alertwaiting2.cancel();
									}
								}
							} );
						}
					}.start();
				}catch (Exception e) {}
			}
		}
	};
	
	private OnClickListener btaddlabelClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Library_All_Label.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			if(txtnamelabel.getText()!= null && !txtnamelabel.getText().toString().equals("")){
				alertwaiting2.show();
				try{
					new Thread(){
						public void run() {
							kq=listlabeldao.addlabel(LoginActivity.database, txtnamelabel.getText().toString(), LoginActivity.emp.getIdemployee());
							uiHandler2.post( new Runnable(){
								@Override
								public void run() {
									if(isUpdateRequired2){
									}else{
										if(kq>0){
											loadlistview();
											txtnamelabel.setText("");
										}
										alertwaiting2.cancel();
									}
								}
							} );
						}
					}.start();
				}catch (Exception e) {}
			}
		}
	};

	private OnClickListener btresetlabelClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			txtnamelabel.setText("");
		}
	};

	private OnClickListener btcloselabelClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			lilaaddlabel.setVisibility(View.GONE);
		}
	};

	public void loadlistview(){
		listlabelvalue=listlabeldao.getAllListLabel(LoginActivity.database,LoginActivity.emp.getIdemployee());
		libarylistadapter = new Library_Listview_Adapter(Library_All_Label.this, listlabelvalue);
		lstalllabel.setAdapter(libarylistadapter);
		int totalHeight_lstapp=0;
		for (int i = 0; i < libarylistadapter.getCount(); i++) {
			View listItem = libarylistadapter.getView(i, null, lstalllabel);
			listItem.measure(0, 0);
			totalHeight_lstapp += listItem.getMeasuredHeight();
		}
		totalHeight_lstapp+= totalHeight_lstapp + (lstalllabel.getDividerHeight() * (libarylistadapter.getCount() - 1));
		ViewGroup.LayoutParams params_lstapp = lstalllabel.getLayoutParams();
		params_lstapp.height=totalHeight_lstapp;
		lstalllabel.setLayoutParams(params_lstapp);
	}
	
	public void loadlistview1(){
		listlabelvalue=listlabeldao.getAllListLabel(LoginActivity.database,LoginActivity.emp.getIdemployee());
	}

	private OnClickListener listenerLogout=new OnClickListener() {

		public void onClick(View v) {
			logout.setTextColor(Color.parseColor("#1188ff"));
			LoginActivity.flagruntimer=true;
			LoginActivity.soluong=0;
			LoginActivity.emp= new Employee();
			MainEApproval.mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
			MainEApproval.timer.cancel();
			Intent i=new Intent(Library_All_Label.this, LogoutActivity.class);
			startActivity(i);
			finish();
		}
	};

	@Override
	public void onBackPressed() {
		alertwaiting2.show();
		try{
			new Thread(){
				public void run(){
					Intent intent = new Intent(Library_All_Label.this,MainEApproval.class);
					startActivity(intent);
					uiHandler2.post(new Runnable() {
						@Override
						public void run() {
							if(isUpdateRequired2){
							}else{
								alertwaiting2.cancel();
							}
						}
					});
					finish();
				}
			}.start();
		}catch(Exception e){}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(LoginActivity.typeLang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu, menu);
		}else if(LoginActivity.typeLang.equals("VN")){
			inflater.inflate(R.menu.option_main_menuvn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menukr, menu);
		}

		setMenuBackground();
		return true;

	}

	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  

			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.drawable.border_footer);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(LoginActivity.typeLang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menu_eappvn:
				processMenuEApproval();
				return true;
			case R.id.menu_primemovn:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(LoginActivity.typeLang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menu_eappkr:
				processMenuEApproval();
				return true;
			case R.id.menu_primemokr:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menu_eapp:
				processMenuEApproval();
				return true;
			case R.id.menu_primemo:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}


	}

	public void processMenuEApproval(){
		Intent intent = new Intent(Library_All_Label.this,MainEApproval.class);
		startActivity(intent);
		finish();
	}

	public void processMenuPrivateMemo(){
		Intent intent = new Intent(Library_All_Label.this,Memo_listview.class);
		startActivity(intent);
		finish();
	}
}
